package moe.oil.email.service;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import moe.oil.api.databaseAPI.UserAPI;
import moe.oil.config.ConfigEmail;
import moe.oil.config.ConfigSecurity;
import moe.oil.dto.user.UserDTO;
import moe.oil.exception.user.EmailNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Setter(onMethod_ = @Autowired)
@Data
@Slf4j
@Service
public class EmailService {

    private JavaMailSenderImpl mailSender;
    private UserAPI userAPI;


    public void send(UserDTO userDTO) {
        String token = createPathLink(userDTO);

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mail = null;
        try {
            mail = new MimeMessageHelper(mimeMessage, true);
            mail.setSubject(ConfigEmail.TITLE);
            mail.setText(ConfigEmail.getHTML(token), true);
            mail.setTo(userDTO.getEmail());  // 接收者
            mail.setFrom(ConfigEmail.FROM);
            mailSender.send(mimeMessage);
            log.info("发送邮件给：{} 成功", userDTO.getEmail());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public String createPathLink(UserDTO userDTO) {
        return Jwts.builder()
                .setExpiration(new Date(new Date().getTime() + ConfigSecurity.EMAIL_EXPIRATION_TIME))
                .setClaims(Map.of("user", userDTO))
                .signWith(SignatureAlgorithm.HS256, ConfigSecurity.SECURITY_KEY)
                .compact();
    }

    public String verify(String token) {

        var data = Jwts.parser()
                .setSigningKey(ConfigSecurity.SECURITY_KEY)
                .parseClaimsJws(token)
                .getBody();
        var map = data.get("user", HashMap.class);


        String email = map.get("email").toString();
        String username = map.get("username").toString();
        String password = map.get("password").toString();


        //todo find email in database
        //todo 过期异常处理
        if (email == null) {
            throw new EmailNotFoundException("邮箱不存在");
        }

        userAPI.insert(new UserDTO().setUsername(username).setPassword(password).setEmail(email));
        return ConfigEmail.URL;
    }
}
